<?php

declare(strict_types=1);

namespace app\admin\service\science;

use app\common\model\AuthenticationModel;
use Dengje\Pxy\BaseService;
use think\Exception;

class AuthenticationService extends BaseService
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new AuthenticationModel();
    }

    /**
     * 获取认证列表
     * @return array
     */
    public function list()
    {
        $where = [];
        $order = ['create_time' => 'desc'];
        
        // 查询参数
        $id= request()->get('id', '');
        $name = request()->get('name', '');
        $user_name = request()->get('user_name', '');
        $category_name= request()->get('category_name', '');
        
        if ($name) $where[] = ['name', 'like', '%' . $name . '%'];
        if ($id) $where[] = ['id', '=', $id];

        $model = $this->model;
        if ($user_name){
            $model = $model->whereExists( function($query) use ($user_name){
                $query->name('user')->where('name', 'like', '%' . $user_name . '%');
            });
        }
        if ($category_name){
            $model = $model->whereExists( function($query) use ($category_name){
                $query->name('territory_cate')->where('name', 'like', '%' . $category_name . '%');
            });
        }
        // 关联用户信息
        $list = $model->where($where)
            ->with(['user' => function($query) {
                $query->field('id, name');
            },'category' => function($query) {
                $query->field('id, name');
            }])
            ->order($order)
            ->paginate(request()->get('page_size/d', 10));
        
        return $list;
    }

    /**
     * 获取认证详情
     * @param int $id
     * @return mixed
     * @throws Exception
     */
    public function detail(int $id)
    {
        $detail = $this->model->where('id', $id)->find();
        if (!$detail) {
            throw new Exception('认证记录不存在');
        }
        
        // 确保information_json是数组格式
        if (!is_array($detail['information_json'])) {
            $detail['information_json'] = json_decode($detail['information_json'], true) ?: [];
        }
        
        return $detail;
    }

    /**
     * 创建认证记录
     * @param $request
     * @return mixed
     */
    public function create($request)
    {
        $data = $this->preExcludeFields($request->param());
        
        $model = [
            'name' => $data['name'],
            'user_id' => $data['user_id'],
            'cate_id' => $data['cate_id'],
            'information_json' => json_encode($data['information_json'] ?? [], JSON_UNESCAPED_UNICODE),
            'create_time' => time(),
            'update_time' => time(),
        ];
        
        $id = $this->model->insertGetId($model);
        return $id;
    }

    /**
     * 更新认证记录
     * @param int $id
     * @param $request
     * @return mixed
     * @throws Exception
     */
    public function update(int $id, $request)
    {
        $data = $this->preExcludeFields($request->param());
        $find = $this->model->where('id', $id)->find();
        if ($find['status'] != 0) {
            throw new Exception('已认证，不能更新');
        }

        $model = [
            'name' => $data['name'],
            'cate_id' => $data['cate_id'],
            'user_id' => $data['user_id'],
            'describe' => $data['describe'],
            'status' => $data['status'],
            'information_json' => json_encode($data['information_json'] ?? [], JSON_UNESCAPED_UNICODE),
            'update_time' => time(),
        ];
        
        $result = $this->model->where('id', $id)->update($model);
        if (!$result) {
            throw new Exception('更新失败');
        }
        
        return $id;
    }

    /**
     * 删除认证记录
     * @return array
     * @throws Exception
     */
    public function delete()
    {
        $ids = request()->param('id/a');
        if (!$ids) {
            throw new Exception('请选择要删除的记录');
        }
        
        $result = $this->model->destroy($ids);
        if (!$result) {
            throw new Exception('删除失败');
        }
        
        return ['affected_rows' => $result];
    }
}